<template>
  <Drawer
    :visible="visible"
    title="数据源规格管理"
    width="50%"
    @close="close"
    :footer-style="{ textAlign: 'right' }"
    placement="right"
    :destroy-on-close="true"
  >
    <template #closeIcon>
      <arrow-left-outlined />
    </template>

    <Form :model="formState" v-bind="formItemLayout" ref="formRef" :rules="configRules">
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="企业项目ID" name="enterpriseProjectId">
            {{ formState.enterpriseProjectId }}
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="区域ID" name="region">
            {{ formState.region }}
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="可用区ID" v-if="dbType == 'rds'" name="availabilityZone">
            {{ formState.availabilityZone }}
          </FormItem>
          <FormItem label="可用区类型" v-if="dbType == 'gaussDb'" name="availabilityZoneMode">
            {{ formState.availabilityZoneMode }}
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem v-if="dbType == 'rds'" label="时区" name="timeZone">
            {{ formState.timeZone }}
          </FormItem>
          <FormItem
            v-if="dbType == 'gaussDb' && formState.availabilityZoneMode == 'multi'"
            label="主可用区"
            name="masterAvailabilityZone"
          >
            {{ formState.masterAvailabilityZone }}
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="VPC ID" name="vpcId">
            {{ formState.vpcId }}
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="子网ID" name="subnetId">
            {{ formState.subnetId }}
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="安全组ID" name="securityGroupId">
            {{ formState.securityGroupId }}
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="时区" name="timeZone">
            {{ formState.timeZone }}
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="数据库引擎" name="datastoreType">
            {{ formState.datastoreType }}
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="数据库版本" name="datastoreVersion">
            <Select
              v-if="dbType == 'rds'"
              v-model:value="formState.datastoreVersion"
              :options="datastoreVersionOpt"
              placeholder="请选择"
            />
            <Select
              v-if="dbType == 'gaussDb'"
              v-model:value="formState.datastoreVersion"
              :options="datastoreVersionOpt"
              placeholder="请选择"
            />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem v-if="dbType == 'rds'" label="磁盘类型" name="volumeType">
            <Select
              v-model:value="formState.volumeType"
              :options="volumeTypeOpt"
              placeholder="请输入"
              :disabled="disableRdsDiskType"
            />
          </FormItem>
          <FormItem v-if="dbType == 'gaussDb'" label="备节点个数" name="slaveCount">
            <InputNumber v-model:value="formState.slaveCount" :min="1" :max="9" placeholder="请选择" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem v-if="dbType == 'rds'" label="磁盘大小" name="volumeSize">
            <InputNumber
              v-model:value="formState.volumeSize"
              :min="40"
              :max="128000"
              :step="10"
              defaultValue="40"
              placeholder="请选择"
            />
            GB
          </FormItem>
          <FormItem v-if="dbType == 'gaussDb'" label="实例类型" name="mode">
            {{ formState.mode }}
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12" v-if="dbType == 'gaussDb'">
          <FormItem label="磁盘大小" name="volumeSize">
            <InputNumber
              v-model:value="formState.volumeSize"
              :min="40"
              :max="128000"
              :step="10"
              defaultValue="40"
              placeholder="请选择"
            />
            GB
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="规格码" name="flavorRef">
            <Select
              v-if="dbType == 'rds'"
              v-model:value="formState.flavorRef"
              :options="flavorRefOpt"
              :disabled="disableFlavor"
              placeholder="请输入"
            />
            <Select
              v-if="dbType == 'gaussDb'"
              v-model:value="formState.flavorRef"
              :options="flavorRefOpt"
              placeholder="请输入"
            />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
          <FormItem label="密码" name="password" :rules="pwdEditable ? pwdRule : []">
            <InputPassword v-if="pwdEditable" v-model:value="formState.password" placeholder="请输入" />
            <template v-if="!pwdEditable">
              {{ formState.password }}
              <a @click="changePwdState(null)"><EditOutlined /></a
            ></template>
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem
            v-if="pwdEditable"
            label="确认密码"
            name="checkPassword"
            :rules="[
              { required: true, message: '确认密码不能为空' },
              { validator: validateCheckPwd, trigger: 'change' },
            ]"
          >
            <InputPassword v-model:value="formState.checkPassword" placeholder="请输入" />
          </FormItem>
        </Col>
      </Row>
    </Form>
    <template #footer>
      <Button style="margin-right: 8px" type="primary" @click="submit">{{ ButtonEnum.SUBMIT }}</Button>
      <Button @click="close">{{ ButtonEnum.CANCEL }}</Button>
    </template>
  </Drawer>
</template>

<script lang="ts" setup>
import { ref, watchEffect } from 'vue';
import { Drawer, Form, FormItem, Col, Row, InputPassword, Button, Select, InputNumber, message } from 'ant-design-vue';
import { ArrowLeftOutlined, EditOutlined } from '@ant-design/icons-vue';

import { configRules, pwdRule } from './data';
import { UpdateParams } from '/@/api/system-mgmt/source-mgmt/model/sourceModel';
import {
  getDbType,
  getGaussDBInstanceInfo,
  getGaussDBSizeCode,
  getGuassDbVersion,
  getRdsDBVersion,
  getRdsDiskType,
  getRdsInstanceInfo,
  getRdsInstanceSizeCode,
  updateGaussDbInstanceInfo,
  updateRdsInstanceInfo,
} from '/@/api/system-mgmt/source-mgmt/source';
import { Rule } from 'ant-design-vue/lib/form';
import { ButtonEnum } from '/@/enums/buttonEnum';
const visible = ref(false);
const formRef = ref();
const dbType = ref();
const formState = ref({} as UpdateParams);
const datastoreVersionOpt = ref();
const flavorRefOpt = ref();

const volumeTypeOpt = ref();
const pwdEditable = ref(false);

const changePwdState = (pwd) => {
  if (pwd) {
    pwdEditable.value = false;
  } else {
    formState.value.password = undefined;
    pwdEditable.value = true;
  }
};
const validateCheckPwd = async (_rule: Rule, value: string) => {
  if (value && value !== formState.value.password) {
    return Promise.reject(new Error('请输入相同密码'));
  } else {
    return Promise.resolve();
  }
};

const openConfigDrawer = async () => {
  visible.value = true;
  dbType.value = await getDbType();
  if (dbType.value == 'rds') {
    formState.value = await getRdsInstanceInfo();
    formState.value.volumeSize = 40;
    changePwdState(formState.value.password);
    datastoreVersionOpt.value = await getRdsDBVersion('MySQL');
  } else if (dbType.value == 'gaussDb') {
    formState.value = await getGaussDBInstanceInfo();

    formState.value.masterAvailabilityZone = '123';
    formState.value.endpoint = 'gaussdb.cn-north-7.myhuaweicloud.com';
    formState.value.volumeSize = 40;
    changePwdState(formState.value.password);
    datastoreVersionOpt.value = await getGuassDbVersion(formState.value.datastoreType);
  }
};
const disableFlavor = ref(true);
const disableRdsDiskType = ref(true);
const setSizeCodeParam = (value: string, database: string) => {
  let sizeCodeParam = {
    versionName: value,
    databaseName: database,
    availabilityZoneMode: formState.value.availabilityZoneMode,
  };
  return sizeCodeParam;
};

watchEffect(async () => {
  if (formState.value.datastoreVersion) {
    if (dbType.value == 'gaussDb') {
      let sizeCodeparam = setSizeCodeParam(formState.value.datastoreVersion, formState.value.datastoreType);
      flavorRefOpt.value = await getGaussDBSizeCode(sizeCodeparam);
    }
    if (dbType.value == 'rds') {
      let sizeCodeparam = setSizeCodeParam(formState.value.datastoreVersion, formState.value.datastoreType);
      flavorRefOpt.value = await getRdsInstanceSizeCode(sizeCodeparam);
      disableFlavor.value = false;
      volumeTypeOpt.value = await getRdsDiskType(sizeCodeparam);
      disableRdsDiskType.value = false;
    }
  }
});

const close = () => {
  visible.value = false;
  formRef.value.clearValidate();
  disableFlavor.value = true;
  disableRdsDiskType.value = true;
  formState.value = {} as UpdateParams;
};
const submit = () => {
  formRef.value.validate().then(async () => {
    if (dbType.value == 'rds') {
      const res = await updateRdsInstanceInfo(formState.value);
      message.success(res);
      close();
    } else if (dbType.value == 'gaussDb') {
      const res = await updateGaussDbInstanceInfo(formState.value);
      message.success(res);
      close();
    }
  });
};

const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 14 },
};
defineExpose({ openConfigDrawer });
</script>
